<template>
  <div class="e-rate" :class="{ readonly: readonly }" @click="handleCheck">
    <div class="item-1" :class="{ active: score === 1 }">1</div>
    <div class="item-2" :class="{ active: score === 2 }">2</div>
    <div class="item-3" :class="{ active: score === 3 }">3</div>
    <div class="item-4" :class="{ active: score === 4 }">4</div>
    <div class="item-5" :class="{ active: score === 5 }">5</div>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
const props = defineProps({
  modelValue: {
    type: Number,
    default: 0
  },
  readonly: {
    type: Boolean,
    default: false
  }
})
const emits = defineEmits(['update:modelValue'])
watch(
  () => props.modelValue,
  value => (score.value = value)
)
const score = ref(props.modelValue)
const handleCheck = event => {
  if (!props.readonly) {
    if (event.target.getAttribute('class').indexOf('1') > 0) {
      score.value = score.value === 1 ? 0 : 1
    }
    if (event.target.getAttribute('class').indexOf('2') > 0) {
      score.value = score.value === 2 ? 0 : 2
    }
    if (event.target.getAttribute('class').indexOf('3') > 0) {
      score.value = score.value === 3 ? 0 : 3
    }
    if (event.target.getAttribute('class').indexOf('4') > 0) {
      score.value = score.value === 4 ? 0 : 4
    }
    if (event.target.getAttribute('class').indexOf('5') > 0) {
      score.value = score.value === 5 ? 0 : 5
    }
    emits('update:modelValue', score.value)
  }
}
</script>

<style lang="less" scoped>
@1: #69dfa8;
@2: #7cdf69;
@3: #cfe157;
@4: #ffaf17;
@5: #ff7043;
.e-rate {
  display: flex;
  justify-content: space-between;
  div[class^='item'] {
    width: 32px;
    height: 32px;
    background-color: @white;
    border: 1px solid #e1e6f0;
    border-radius: 2px;
    color: #e1e6f0;
    line-height: 30px;
    text-align: center;
    cursor: pointer;
  }
  .item-1 {
    &.active,
    &:hover {
      border: 1px solid @1;
      color: @1;
    }
  }
  .item-2 {
    &.active,
    &:hover {
      border: 1px solid @2;
      color: @2;
    }
  }
  .item-3 {
    &.active,
    &:hover {
      border: 1px solid @3;
      color: @3;
    }
  }
  .item-4 {
    &.active,
    &:hover {
      border: 1px solid @4;
      color: @4;
    }
  }
  .item-5 {
    &.active,
    &:hover {
      border: 1px solid @5;
      color: @5;
    }
  }
  &.readonly {
    div[class^='item'] {
      cursor: not-allowed;
      &:not(.active) {
        &:hover {
          border: 1px solid #e1e6f0;
          color: #e1e6f0;
        }
      }
    }
  }
}
</style>
